package org.example.juc.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExample {
    public static void main(String[] args) {
        // 创建定时线程池
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

        // 定时任务：延迟 2 秒后执行一次
        scheduler.schedule(() -> {
            System.out.println("Task executed after 2 seconds delay.");
        }, 2, TimeUnit.SECONDS);

        // 周期性任务：每 3 秒执行一次
        scheduler.scheduleAtFixedRate(() -> {
            System.out.println("Periodic task executed every 3 seconds.");
        }, 0, 3, TimeUnit.SECONDS);

        // 注意：为了示范目的，主线程睡眠一段时间
        try {
            Thread.sleep(10000); // 主线程睡眠 10 秒
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 关闭线程池
        scheduler.shutdown();
    }
}
